<script setup lang="ts">
import { DeviceInfo } from "@/components/DeviceInfo";
import { ConnectDevice, ConnectWifi, APISetting } from "@/components/Dialog";
import { BirthdayDate, ColorPicker, WeatherCityPicker } from "@/components/Popup";
import { ref, reactive, onMounted, ComputedRef, computed } from "vue";
import { useConfigStore } from "@/stores/models/config";
import { NavBar, CellGroup, Cell, showNotify, Switch, Icon } from "vant";
import axios from "axios";
import { Loading } from "@/components/Overlay";

const configStore = useConfigStore();

const connectDeviceRef = ref<InstanceType<typeof ConnectDevice> | null>(null);
const connectWifiRef = ref<InstanceType<typeof ConnectWifi> | null>(null);
const APISettingRef = ref<InstanceType<typeof APISetting> | null>(null);
const birthdayDateRef = ref<InstanceType<typeof BirthdayDate> | null>(null);
const colorPickerRef = ref<InstanceType<typeof ColorPicker> | null>(null);
const weatherCityPickerRef = ref<InstanceType<typeof WeatherCityPicker> | null>(null);

const state = reactive<{
    connecting: boolean;
    settingUpMirrorFlip: boolean;
    settingUpLed: boolean;
}>({
    connecting: true,
    settingUpMirrorFlip: false,
    settingUpLed: false
});

onMounted(async () => {
    state.connecting = true;
    if (configStore.device_ip) {
        try {
            const response = await axios({
                url: `http://${configStore.device_ip}/system/info`,
                method: "get",
                timeout: 1000 * 10
            });
            configStore.updateDeviceConfig(response.data);
            showNotify({
                type: "success",
                message: "连接成功"
            });
        } catch (error) {
            showNotify({
                type: "danger",
                message: "连接失败"
            });
            connectDeviceRef.value?.show();
        }
    } else {
        connectDeviceRef.value?.show();
    }
    state.connecting = false;
});

const birthdayDate: ComputedRef<string> = computed(() => {
    const date = configStore.birthday_date.split("-");
    return `${date[0]}月${date[1]}日`;
});

const setScreenMirrorFlip = async (mirror_flip: boolean): Promise<void> => {
    try {
        state.settingUpMirrorFlip = true;
        await axios({
            url: `http://${configStore.device_ip}/set/mirror_flip`,
            method: "post",
            data: {
                mirror_flip
            }
        });

        showNotify({
            type: "success",
            message: "设置成功"
        });
    } catch (error) {
        configStore.$patch({
            mirror_flip: !mirror_flip
        });
        console.log(error);
        showNotify({
            type: "danger",
            message: "设置失败"
        });
    } finally {
        state.settingUpMirrorFlip = false;
    }
};

const setLedStatus = async (status: boolean): Promise<void> => {
    try {
        state.settingUpLed = true;
        await axios({
            url: `http://${configStore.device_ip}/set/rgb/status`,
            method: "post",
            data: {
                status
            }
        });

        showNotify({
            type: "success",
            message: "设置成功"
        });
    } catch (error) {
        configStore.$patch({
            led: {
                status: !status
            }
        });
        console.log(error);
        showNotify({
            type: "danger",
            message: "设置失败"
        });
    } finally {
        state.settingUpLed = false;
    }
};
</script>
<template>
    <NavBar title="ESP32S3 透明小电视" fixed placeholder>
        <template #right>
            <Icon name="link-o" size="20px" @click="connectDeviceRef?.show(true)" />
        </template>
    </NavBar>
    <DeviceInfo />
    <ConnectDevice ref="connectDeviceRef" />
    <ConnectWifi ref="connectWifiRef" />
    <APISetting ref="APISettingRef" />

    <BirthdayDate ref="birthdayDateRef" />
    <ColorPicker ref="colorPickerRef" />
    <WeatherCityPicker ref="weatherCityPickerRef" />

    <Loading :show="state.connecting" text="连接中..." />

    <CellGroup title="网络设置">
        <Cell
            is-link
            title="连接WIFI"
            :value="configStore.wifi.name"
            @click="connectWifiRef?.show()"
        />
    </CellGroup>
    <CellGroup title="天气设置">
        <Cell
            is-link
            title="设置城市"
            :value="configStore.weather.city"
            @click="weatherCityPickerRef?.show()"
        />
    </CellGroup>
    <CellGroup title="RGB设置">
        <Cell title="LED开关">
            <template #extra>
                <Switch
                    size="20px"
                    :loading="state.settingUpLed"
                    v-model="configStore.led.status"
                    @change="setLedStatus"
                />
            </template>
        </Cell>
        <Cell is-link title="RGB颜色" @click="colorPickerRef?.show()">
            <template #value>
                <div
                    style="width: 24px; height: 100%; float: right; border-radius: 3px"
                    :style="{ backgroundColor: `rgb(${configStore.led.rgb.join(',')})` }"
                ></div>
            </template>
        </Cell>
    </CellGroup>
    <CellGroup title="API设置">
        <Cell is-link title="API" :value="configStore.server_api" @click="APISettingRef?.show()" />
        <Cell
            is-link
            title="SECRET_ID"
            :value="configStore.secret_id"
            @click="APISettingRef?.show()"
        />
        <Cell
            is-link
            title="SECRET_KEY"
            :value="configStore.secret_key"
            @click="APISettingRef?.show()"
        />
    </CellGroup>
    <CellGroup title="其它设置">
        <Cell is-link title="生日日期" :value="birthdayDate" @click="birthdayDateRef?.show()" />
        <Cell title="屏幕镜像">
            <template #extra>
                <Switch
                    size="20px"
                    :loading="state.settingUpMirrorFlip"
                    v-model="configStore.mirror_flip"
                    @change="setScreenMirrorFlip"
                />
            </template>
        </Cell>
    </CellGroup>
</template>
